package system

import (
	"fmt"
	"WchimeGinSystem/conf"
	"WchimeGinSystem/models"
	"WchimeGinSystem/utils"
	"WchimeGinSystem/utils/cache"
	"WchimeGinSystem/utils/errmsg"
	jwtauth "WchimeGinSystem/utils/jwtAuth"
	"time"

	"github.com/gin-gonic/gin"
)

type LoginReq struct {
	Username string `json:"username" binding:"required"` // 用户名
	Password string `json:"password" binding:"required"` // 密码
}

type LoginRes struct {
	ID       int    `json:"id"`       //用户ID
	Username string `json:"username"` // 用户名
	Token    string `json:"token"`    // token
	Avatar   string `json:"avatar"`   // 头像
	Mobile   string `json:"mobile"`   //手机号
}

// Login
// @Summary 登录
// @Description 登录
// @Tags 登录
// @Accept json
// @Produce json
// @Param req body LoginReq true "入参"
// @Success 200 {object} LoginRes "返回"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /login [post]
func Login(c *gin.Context) {

	var body LoginReq

	if err := c.ShouldBindJSON(&body); err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_PARAMS_VALID, "")
		return
	}

	user, err := checkUser(body.Username)

	if err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_LOGIN_ERR, "")
		return
	}

	err = utils.CheckPassword(user.Password, body.Password)
	if err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_LOGIN_ERR, "")
		return
	}

	token, err := jwtauth.CreateToken(int64(user.Id))
	if err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}

	// cache.RDB.Set()
	login_k := fmt.Sprintf("%s_%s", conf.SERVER_NAME, string(user.Id))
	err = cache.RDB.Set(cache.CTX, login_k, token, 7200*time.Second).Err()
	if err != nil {
		utils.RespContext(c).ErrorResp(nil, errmsg.ERROR_BASE, "")
		return
	}

	res := LoginRes{
		ID:       user.Id,
		Username: user.Username,
		Token:    token,
		Mobile:   user.Mobile,
		Avatar:   user.Avatar,
	}
	utils.RespContext(c).SuccessResp(res)

}

func checkUser(username string) (models.User, error) {

	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	return user, err

}
